<template>
    <Layout style="height: 100%" class="adminMain">
        <Sider
            hide-trigger
            collapsible
            :width="256"
            :collapsed-width="64"
            v-model="collapsed"
            class="left-sider"
            :style="{overflow: 'hidden'}"
        >
            <side-menu
                accordion
                ref="sideMenu"
                :active-name="$route.name"
                :collapsed="collapsed"
                @on-select="turnToPage"
                :menu-list="menuList"
            >
                <!-- 需要放在菜单上面的内容，如Logo，写在side-menu标签内部，如下 -->
                <div class="logo-con">
                    <div v-show="!collapsed" class="max">
                        <!-- <img :src="theme == 'dark' ? logoDark : logoLight" key="max-logo" /> -->
                        <img :src="getImg(2)" key="max-logo" class="img1" />
                        <!-- <label>卓强物联科技</label> -->
                        <img :src="getImg(1)" key="max-logo1" class="img2" />
                    </div>
                    <div v-show="collapsed" class="min">
                        <!-- <img :src="theme == 'dark' ? logoDark : logoLight" key="min-logo" /> -->
                        <img :src="getImg(2)" key="min-logo" class="img3" />
                    </div>
                </div>
            </side-menu>
        </Sider>
        <Layout>
            <Header class="header-con">
                <header-bar :collapsed="collapsed" @on-coll-change="handleCollapsedChange">
                    <Tooltip content="主题设置" placement="bottom">
                        <div class="set" @click="showSet">
                            <i class="bi bi-three-dots-vertical" style="font-size: 20px"></i>
                        </div>
                    </Tooltip>

                    <user :message-unread-count="unreadCount" :user-avatar="userAvatar" />
                    <language v-if="$config.useI18n" @on-lang-change="setLocal" style="margin-right: 10px" :lang="local" />
                    <error-store
                        v-if="$config.plugin['error-store'] && $config.plugin['error-store'].showInHeader"
                        :has-read="hasReadErrorPage"
                        :count="errorCount"
                    ></error-store>

                    <!-- 暂时禁用 -->
                    <!-- <div class="searchMenu">
                        <childMenuSearch></childMenuSearch>
                    </div> -->

                    <fullscreen v-model="isFullscreen" />

                    <div class="full-screen-btn-con">
                        <Tooltip content="中枢平台" placement="bottom">
                            <div class="set" @click="showCenter">
                                <Icon :type="'md-home'" :size="23"></Icon>
                            </div>
                        </Tooltip>
                    </div>

                    <div class="full-screen-btn-con">
                        <img :src="jqr" key="jqr" style="margin-top: 20px; cursor: pointer" />
                    </div>
                </header-bar>
            </Header>
            <Content class="main-content-con">
                <Layout class="main-layout-con">
                    <div class="tag-nav-wrapper">
                        <tags-nav :value="$route" @input="handleClick" :list="tagNavList" @on-close="handleCloseTag" />
                    </div>
                    <Content class="content-wrapper">
                        <keep-alive :include="cacheList">
                            <router-view />
                        </keep-alive>
                        <ABackTop :height="100" :bottom="80" :right="50" container=".content-wrapper"></ABackTop>
                    </Content>
                </Layout>
            </Content>
        </Layout>
        <drag-drawer v-model="showWindowBDrawer" width="280" :min-width="200" placement="right" :draggable="false" :scrollable="true">
            <themeSet @getTheme="getTheme" />
        </drag-drawer>

        <div class="leftBottomTooltip" v-if="showBottomTooltip && !collapsed" @mouseover="showZqwl = true">
            <img :src="logoDark" class="imgLogo" @click="showZqwl = true" />
            <div>
                <img src="../../assets/images/1030/closeSmall.svg" class="imgClose" @click="showBottomTooltip = false" />
            </div>
        </div>
        <div class="zqwl" v-if="showZqwl && !collapsed">
            <div class="logo">
                <img src="../../assets/images/1030/logo.svg" class="imgLogo" />
                <!-- <span>卓强物联科技</span> -->
            </div>
            <div class="gzh">
                <img src="../../assets/images/1030/公众号.svg" />
            </div>
            <div>
                <label> 开发单位：湖南卓强物联科技有限公司 </label>
                <label> 版权所有：Copyright(©2009-2024) </label>
                <label> 服务热线：400-932-9896 </label>
                <label> 版本编号：V3.0.0bata </label>
            </div>
            <img src="../../assets/images/1030/closeBig.svg" class="imgBigClose" @click="showZqwl = false" />
        </div>
    </Layout>
</template>
<script>
import logoDark from '@/assets/images/logo/logo.png'
// import maxLogo from '@/assets/images/logo.jpg'
import logoLight from '@/assets/images/logo/logoLight.png'
import Rgzn from '@/assets/images/index/kf1.png'
import {getNewTagList, routeEqual} from '@/libs/util'
import routers from '@/router/routers'
import DragDrawer from '_c/drag-drawer'
import {mapActions, mapGetters, mapMutations} from 'vuex'
import childMenuSearch from '../../components/main/components/theme/childMenuSearch'
import themeSet from '../../components/main/components/theme/themeSet'
import ABackTop from './components/a-back-top'
import ErrorStore from './components/error-store'
import Fullscreen from './components/fullscreen'
import HeaderBar from './components/header-bar'
import Language from './components/language'
import SideMenu from './components/side-menu'
import TagsNav from './components/tags-nav'
import User from './components/user'
import './main.less'
import {setToken} from '@/libs/util'
import {ManagementCenterData} from '@/mockData/managementCenterData.js'
import {Utility} from '@/libs/utility'
export default {
    name: 'Main',
    components: {
        SideMenu,
        HeaderBar,
        Language,
        TagsNav,
        Fullscreen,
        ErrorStore,
        User,
        ABackTop,
        DragDrawer,
        themeSet,
        childMenuSearch
    },
    data() {
        return {
            showBottomTooltip: true,
            showZqwl: false,
            showWindowBDrawer: false,
            collapsed: false,
            logoDark,
            logoLight,
            isFullscreen: false,
            theme: 'dark',
            jqr: Rgzn
        }
    },
    computed: {
        ...mapGetters(['errorCount']),
        tagNavList() {
            // Todo.............退出登录或者进入中枢平台应该将tagNavList清空  TODO.................
            return this.$store.state.app.tagNavList
        },
        tagRouter() {
            return this.$store.state.app.tagRouter
        },
        userAvatar() {
            // 获取用户信息
            const sex = JSON.parse(localStorage.getItem('userInfo'))?.sex
            if (sex == '0') {
                return require('@/assets/images/girlImg.png')
            } else {
                return require('@/assets/images/boyImg.png')
            }
            // return this.$store.state.user.avatarImgPath
        },
        cacheList() {
            const list = [
                'ParentView',
                ...(this.tagNavList.length
                    ? this.tagNavList.filter((item) => !(item.meta && item.meta.notCache)).map((item) => item.name)
                    : [])
            ]
            // 去重，这个地方不去重，会导致经常出现两个首页
            const uniqueArr = [...new Set(list)]
            return uniqueArr
        },
        menuList() {
            const childSysMenuPower = sessionStorage.getItem('childSysMenuPower')
            if (childSysMenuPower == null) {
                sessionStorage.setItem('ALLMENULIST', '')
                localStorage.removeItem('userInfo')
                sessionStorage.setItem('menuInfo', '')
                setToken('')
                localStorage.tagNaveList = ''
                this.handleLogOut().then(() => {
                    this.$router.push({
                        name: 'userLogin'
                    })
                })
                return
            }
            const childSysList = JSON.parse(childSysMenuPower)
            // // 所有的系统菜单权限
            const menuList = this.$store.getters.menuList
            let allMenu = []
            const largeScreen = childSysList.find((t) => t.menu_url == 'largeScreen')
            let menuItem = {}
            // 系统驾驶舱
            if (largeScreen != null) {
                allMenu.push(menuList[0])
            }
            const mcMainIndex = childSysList.find((t) => t.menu_url == 'mcMainIndex')
            // 监控中心
            if (mcMainIndex != null) {
                allMenu.push(menuList[1])
            }
            let children = []
            // 控制中心 controlCenter
            const controlCenter = childSysList.find((t) => t.menu_url == 'controlCenter')
            if (controlCenter != null) {
                menuItem = JSON.parse(JSON.stringify(menuList[2]))
                allMenu.push(this.getFirstMenu(menuItem, controlCenter))
            }
            // 财务中心
            const financialCenter = childSysList.find((t) => t.menu_url == 'financialCenter')
            if (financialCenter != null) {
                menuItem = JSON.parse(JSON.stringify(menuList[3]))
                allMenu.push(this.getFirstMenu(menuItem, financialCenter))
            }
            // 数据分析中心 dataAnalysisCenter
            const dataAnalysisCenter = childSysList.find((t) => t.menu_url == 'dataAnalysisCenter')
            if (dataAnalysisCenter != null) {
                menuItem = JSON.parse(JSON.stringify(menuList[4]))
                allMenu.push(this.getFirstMenu(menuItem, dataAnalysisCenter))
            }
            // 统计报表中心 dataReportCenter
            const dataReportCenter = childSysList.find((t) => t.menu_url == 'dataReportCenter')
            if (dataReportCenter != null) {
                menuItem = menuList[5]
                allMenu.push(this.getFirstMenu(menuItem, dataReportCenter))
            }
            // 预警告警中心 warnCenterParent
            const warnCenterParent = childSysList.find((t) => t.menu_url == 'warnCenterParent' || t.menu_url == 'warnCenter')
            if (warnCenterParent != null) {
                allMenu.push(menuList[6])
            }
            // 系统管理中心 systemManage
            const systemManage = childSysList.find((t) => t.menu_url == 'systemManage' || t.menu_name == '系统管理中心')
            if (systemManage != null) {
                menuItem = JSON.parse(JSON.stringify(menuList[7]))
                // 查询有几个子菜单
                const systemManageId = systemManage?.children?.map((t) => t.menu_url) ?? []
                let children = menuItem.children.filter((t) => systemManageId?.includes(t.name))
                let finallyChildren = []
                let data = []
                if (children && children.length > 0) {
                    // 机构单位 institutionalUnitManagement
                    let institutionalUnitManagement = children.find((t) => t.name == 'institutionalUnitManagement')
                    data = this.getFinallyMenu(institutionalUnitManagement, 'institutionalUnitManagement', systemManage)
                    if (data != null) {
                        finallyChildren.push(data)
                    }
                    // 菜单管理 menuManage
                    let menuManage = children.find((t) => t.name == 'menuManage')
                    data = this.getFinallyMenu(menuManage, 'menuManage', systemManage)
                    if (data != null) {
                        finallyChildren.push(data)
                    }
                    // 系统管理 systemManageChild
                    let systemManageChild = children.find((t) => t.name == 'systemManageChild')
                    data = this.getFinallyMenu(systemManageChild, 'systemManageChild', systemManage)
                    if (data != null) {
                        finallyChildren.push(data)
                    }
                    // 指标配置 indicatorConfig
                    let indicatorConfig = children.find((t) => t.name == 'indicatorConfig')
                    data = this.getFinallyMenu(indicatorConfig, 'indicatorConfig', systemManage)
                    if (data != null) {
                        finallyChildren.push(data)
                    }
                    // 预警告警管理 warningAlarmManage
                    let warningAlarmManage = children.find((t) => t.name == 'warningAlarmManage')
                    data = this.getFinallyMenu(warningAlarmManage, 'warningAlarmManage', systemManage)
                    if (data != null) {
                        finallyChildren.push(data)
                    }
                    // 日志管理 logManager
                    let logManager = children.find((t) => t.name == 'logManager')
                    data = this.getFinallyMenu(logManager, 'logManager', systemManage)
                    if (data != null) {
                        finallyChildren.push(data)
                    }
                    // 模版管理 templatesManage
                    let templatesManage = children.find((t) => t.name == 'templatesManage')
                    data = this.getFinallyMenu(templatesManage, 'templatesManage', systemManage)
                    if (data != null) {
                        finallyChildren.push(data)
                    }
                }
                if (finallyChildren.length > 0) {
                    menuItem.children = finallyChildren
                    allMenu.push(menuItem)
                }
            }
            return allMenu
            // return menuList
        },
        local() {
            return this.$store.state.app.local
        },
        hasReadErrorPage() {
            return this.$store.state.app.hasReadErrorPage
        },
        unreadCount() {
            return this.$store.state.user.unreadCount
        }
    },
    methods: {
        ...mapMutations(['setBreadCrumb', 'setTagNavList', 'addTag', 'setLocal', 'setHomeRoute', 'closeTag']),
        ...mapActions(['handleLogin', 'getUnreadMessageCount', 'handleLogOut']),
        getImg(type) {
            let userInfo = localStorage.getItem('userInfo') ?? ''
            if (userInfo) {
                userInfo = JSON.parse(userInfo)
                const orgName = userInfo.orgName.indexOf('-') ? userInfo.orgName.split('-')[0] : userInfo.orgName
                // logo图片
                if (type == '1') {
                    return require(`@/assets/images/1030/${orgName}.svg`)
                } else {
                    // 文字图片显示
                    return require(`@/assets/images/1030/${orgName}_logo.svg`)
                }
            }
            return require('@/assets/images/logo/logo.png')
        },
        turnToPage(route) {
            console.log(this.$route.name, route)

            let {name, params, query} = {}
            if (typeof route === 'string') name = route
            else {
                name = route.name
                params = route.params
                query = route.query
            }
            if (name.indexOf('isTurnByHref_') > -1) {
                window.open(name.split('_')[1])
                return
            }
            this.$router.push({
                name,
                params,
                query
            })
        },
        showCenter() {
            // 清空当前记录的菜单
            window.sessionStorage.setItem('menuInfo', '')
            this.$router.push({
                // name: "mcIndex",
                name: 'indexMain'
            })
        },
        getTheme(theme) {
            this.theme = theme
        },
        handleCollapsedChange(state) {
            this.collapsed = state
            setTimeout(() => {
                if (this.theme == 'dark') {
                    document.getElementsByClassName('left-sider')[0].classList.remove('ivu-layout-sider-light')
                    document.getElementsByClassName('left-sider')[0].classList.add('ivu-layout-sider')
                } else {
                    document.getElementsByClassName('left-sider')[0].classList.remove('ivu-layout-sider')
                    document.getElementsByClassName('left-sider')[0].classList.add('ivu-layout-sider-light')
                }
            })
        },
        showSet() {
            this.showWindowBDrawer = true
        },
        handleCloseTag(res, type, route) {
            if (type !== 'others') {
                if (type === 'all') {
                    this.turnToPage(this.$config.homeName)
                } else {
                    if (routeEqual(this.$route, route)) {
                        this.closeTag(route)
                    }
                }
            }
            this.setTagNavList(res)
        },
        getFirstMenu(menuItem, menuData) {
            const ids = menuData?.children?.map((t) => t.menu_url) ?? []
            const children = menuItem.children.filter((t) => ids.includes(t.name))
            menuItem.children = ids.length > 0 ? children : []
            return menuItem
        },
        getFinallyMenu(nameData, name, systemManage) {
            let threeChild = []
            let ids = []
            if (nameData != null) {
                const data = systemManage?.children?.find((t) => t.menu_url == name)
                if (data?.children && data?.children?.length > 0) {
                    ids = data?.children?.map((t) => t.menu_url)
                    threeChild = nameData.children.filter((t) => ids.includes(t.name))
                    nameData.children = threeChild
                    return nameData
                } else {
                    return null
                }
            } else {
                return null
            }
        },
        handleClick(item) {
            this.turnToPage(item)
        }
    },
    watch: {
        $route(newRoute) {
            const {name, query, params, meta} = newRoute
            this.addTag({
                route: {name, query, params, meta},
                type: 'push'
            })
            this.setBreadCrumb(newRoute)
            this.setTagNavList(getNewTagList(this.tagNavList, newRoute))
            this.$refs.sideMenu.updateOpenName(newRoute.name)
        }
    },
    mounted() {
        /**
         * @description 初始化设置面包屑导航和标签导航
         */
        this.setTagNavList()
        this.setHomeRoute(routers)
        const {name, params, query, meta} = this.$route
        this.addTag({
            route: {name, params, query, meta}
        })
        this.setBreadCrumb(this.$route)
        // // 设置初始语言
        // this.setLocal(this.$i18n.locale)
        // 如果当前打开页面不在标签栏中，跳到homeName页
        if (!this.tagNavList.find((item) => item.name === this.$route.name)) {
            this.$router.push({
                name: this.$config.homeName
            })
        }
        // 获取未读消息条数
        // this.getUnreadMessageCount()
    }
}
</script>
